<template>
  <div class="search-container" :style="!isHomePage?'padding-top: 56px':'padding-top: 70px'">
    <div class="search-box-wrapper">
      <div class="search-row">
        <div class="articleType dropdown" @click="toggleDropdown" role="combobox" aria-expanded="isDropdownShow"
          aria-haspopup="listbox" ref="dropdown">
          <span class="rigName" :data-name="currentOption.retrieveConfigName">{{
            currentOption.retrieveConfigName
          }}</span>
          <i class="iconfont icon-xiala1 rigNamei"></i>

          <div class="dropdown-options" v-if="isDropdownShow" 
            aria-label="搜索范围选项">
            <div class="dropdown-option" v-for="option in dropdownOptions" :key="option.retrieveConfigId"
              @click.stop="handleOptionClick(option)" :aria-selected="currentOption.retrieveConfigId === option.retrieveConfigId
                " :title="option.retrieveConfigName">
              {{ option.retrieveConfigName }}
            </div>
          </div>
        </div>
        <div style="
            background-color: #fff;
            height: 100%;
            display: flex;
            align-items: center;
          ">
          <div style="width: 1px; height: 55px; background-color: #e4e4e4"></div>
        </div>

        <input type="text" class="search-input" placeholder="检索" v-model="searchValue" @keyup.enter="handleSearch"
          @focus="showSearchPanel" @input="handleInputChange" ref="searchInput" />

        <div class="search-panel" v-if="historyShow && (leftData.words?.length || rightData.words?.length)"
          ref="searchPanel">
          <div class="panel">
            <div class="panel-column">
              <div class="title">
                <div>{{ leftData.type }}</div>
                <el-button class="title-hun" type="text" v-if="leftData.type === '搜索历史'"
                  @click.stop="ALLdeleteSearchHistory(leftData.type)">全部清除</el-button>
              </div>
              <ul>
                <li v-for="item in leftData.words" :key="item.word">
                  <div @click="handleHistoryClick(item.originalWord)" class="zi" v-html="item.word" />

                  <div class="caoz">
                    <i v-if="leftData.type === '搜索历史'" @click="deleteSearchHistory(item, '搜索历史')"
                      class="el-icon-close"></i>
                    <div v-else>标错</div>
                  </div>
                </li>
              </ul>
            </div>
            <div style="width: 1px; height: 463px; background-color: #e4e4e4"></div>
            <div class="panel-column">
              <div class="title">
                <div>{{ rightData.type }}</div>
                <el-button class="title-hun" type="text" v-if="rightData.type === '热门搜索'"
                  @click.stop="ALLdeleteSearchHistory(rightData.type)">全部清除</el-button>
              </div>
              <ul>
                <li v-for="item in rightData.words" :key="item.word">
                  <div @click="handleHistoryClick(item.originalWord)" class="zi" v-html="item.word" />

                  <div class="caoz">
                    <i v-if="rightData.type === '热门搜索'" @click="deleteSearchHistory(item, '热门搜索')"
                      class="el-icon-close"></i>
                    <div v-else>标错</div>
                  </div>
                </li>
              </ul>
            </div>
          </div>

          <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page.sync="currentPage" :page-size="pageSize" layout="prev, pager, next" :total="totalCount"
              prev-text="上一页" next-text="下一页">
            </el-pagination>
          </div>
        </div>

        <div class="search-btn-wrapper">
          <div v-if="searchValue.trim() && (!leftData.words?.length && !rightData.words?.length)" style="
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 18px;
              color: #327dff;
              cursor: pointer;
              margin: 0 25px;
            ">
            + 添加为新词
          </div>
          <el-button class="search-btn" type="primary" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
        </div>

        <button class="advanced-search-btn" @click="handleAdvancedSearch">
          高级检索 <i class="iconfont icon-z044-copy"></i>
        </button>
      </div>

      <div class="search-tags">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0"></div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="city in cities" :label="city.typeId" :value="city.typeId" :key="city.typeId">{{
            city.typeName }}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import service from "@/service/service";

export default {
  name: "SearchComponent",
  data() {
    return {
      dropdownOptions: [],
      currentOption: {},
      isDropdownShow: false,
      searchTipMethod: 0,
      searchValue: "",
      checkAll: true,
      checkedCities: [],
      cities: [],
      isIndeterminate: false,
      debounceTimer: null,
      historyShow: false,
      leftData: {
        words: [],
      },
      rightData: {
        words: [],
      },
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
    };
  },
 computed: {
    isHomePage() {
      return this.$route.path === "/home";
    },
  },
  created() {
    this.getSearchFields();
    this.getAllTypes();
  },
  methods: {
    ...mapActions(["updateCheckedCities", "updateCurrentOption"]),



    //  删除历史记录、或者热搜
    async deleteSearchHistory(row, type) {
      try {
        const response = await service({
          url: "/frontend/retrieve/delSearchHistory",
          method: "post",
          data: {
            type,
            words: [row.word],
          },
        });
        if (response.code === 200) {
          this.getSearchTip();
        } else {
          this.$message.error(response.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }




    },
    ALLdeleteSearchHistory(type) {
      this.$confirm('确定要全部清除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await service
            .post("/frontend/retrieve/delSearchHistory", {
              type,
              words: type == '热门搜索' ? this.rightData.words.map(item => item.word) : this.leftData.words.map(item => item.word),
            });
          if (response.code === 200) {
            this.getSearchTip();
          } else {
            this.$message.error(response.msg);
          }
        } catch (error) {
          this.$message.error(error);
        }
      }).catch(() => {

      });
    },



    //获取搜索字段
    async getSearchFields() {
      try {
        const response = await service({
          url: "/frontend/index/getAllRetrieveNames",
          method: "get",
        });
        if (response.code === 200) {
          this.dropdownOptions = response.data;
          this.currentOption = this.dropdownOptions[0];
          this.updateCurrentOption(this.currentOption.retrieveConfigId);
        } else {
          this.$message.error(response.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    // 获取所有类型列表
    async getAllTypes() {
      try {
        const response = await service({
          url: "/frontend/index/typeList",
          method: "post",
          data: {
            pageSize: 100,
            pageNo: 1,
          },
        });
        if (response.code === 200) {
          this.cities = response.data.list;
          this.checkedCities = this.cities.map((city) => city.typeId);
          this.checkAll = true;
          this.isIndeterminate = false;
          this.updateCheckedCities(this.checkedCities);
        } else {
          this.$message.error(response.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    //搜索提示
    async getSearchTip() {
      try {
        const response = await service({
          url: "/frontend/retrieve/tip",
          method: "post",
          data: {
            pageNo: this.currentPage,
            pageSize: this.pageSize,
            word: this.searchValue,
            type: 0,
          },
        });
        if (response.code === 200) {
          if (response.data.list.length > 0) {
            this.leftData = response.data.list[0].left;
            this.rightData = response.data.list[0].right;
          } else {
            this.leftData = {
              words: [],
            };
            this.rightData = {
              words: [],
            };
          }
          this.totalCount = response.data.total;
        } else {
          this.$message.error(response.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },

    handleNextBatch() {
      if (this.currentPage * this.pageSize < this.totalCount) {
        this.currentPage++;
      } else {
        this.currentPage = 1;
      }
      this.getSearchTip();
    },

    // 分页处理方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 改变每页显示数量时重置到第一页
      this.getSearchTip();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.getSearchTip();
    },

    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities.map((city) => city.typeId) : [];
      this.isIndeterminate = false;
      this.updateCheckedCities(this.checkedCities);
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
      this.updateCheckedCities(value);
    },
    toggleDropdown() {
      this.isDropdownShow = !this.isDropdownShow;
    },
    handleOptionClick(option) {
      this.currentOption = option;
      this.isDropdownShow = false;
      this.updateCurrentOption(this.currentOption.retrieveConfigId);

      const tipMethodMap = { 3: 1, 4: 2 };
      this.searchTipMethod = tipMethodMap[option.id] || 0;
    },
    handleSearch() {
      if (this.$route.query.type) {
        this.$router.push({
          path: "/SearchPage",
          query: {
            type: this.$route.query.type,
            keyword: this.searchValue,
          },
        });
      } else {
        this.$router.push({
          path: "/SearchPage",
          query: {
            keyword: this.searchValue,
          },
        });
      }

      clearTimeout(this.debounceTimer);

      this.debounceTimer = setTimeout(() => {
        if (!this.searchValue.trim()) {
          console.warn("请输入搜索关键词");
          return;
        }

        console.log("搜索参数：", {
          type: this.currentOption.name,
          keyword: this.searchValue.trim(),
          tipMethod: this.searchTipMethod,
          checkedCities: this.checkedCities,
        });
      }, 300);
    },
    handleAdvancedSearch() {
      console.log("打开高级检索");
      this.$emit("openAdvancedSearch");
      this.$router.push({ path: "/SearchPage?advanced=true" });
    },

    handleClickOutside(e) {
      // 处理下拉菜单点击外部关闭
      if (this.$refs.dropdown && !this.$refs.dropdown.contains(e.target)) {
        this.isDropdownShow = false;
      }

      // 处理搜索面板点击外部关闭
      if (this.historyShow) {
        const searchInput = this.$refs.searchInput;
        const searchPanel = this.$refs.searchPanel;
        if (searchInput && searchPanel) {
          if (
            !searchInput.contains(e.target) &&
            !searchPanel.contains(e.target)
          ) {
            this.historyShow = false;
          }
        }
      }
    },
    // 新增：搜索面板显示/隐藏方法
    showSearchPanel() {
      this.currentPage = 1; // 重置页码
      this.getSearchTip();
      this.historyShow = true;
    },
    handleInputChange() {
      this.currentPage = 1; // 输入时重置页码
      this.getSearchTip();
    },
    // 新增：点击历史项触发搜索
    handleHistoryClick(item) {
      this.searchValue = item;
      this.handleSearch();
    },
    // 新增：点击热门项触发搜索
    handleHotClick(item) {
      this.searchValue = item;
      this.handleSearch();
    },
  },
  mounted() {
    document.addEventListener("click", this.handleClickOutside);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.handleClickOutside);
    clearTimeout(this.debounceTimer);
  },
};
</script>


<style lang="scss" scoped>
.caoz {
  i {
    font-size: 20px;
    color: #666666;

    &:hover {
      color: #327dff;
    }
  }

  div {
    &:hover {
      color: #327dff;
    }
  }
}

.rigNamei {
  font-size: 10px;
  color: #999999;
}

.rigName {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 18px;
  color: #333333;
  white-space: nowrap; // 防止文本换行
  overflow: hidden; // 隐藏溢出内容
  text-overflow: ellipsis; // 显示省略号
}

$primary-color: #327dff;
$secondary-color: #7caaff;
$text-color: #333;
$text-light-color: #666;
$border-radius: 8px;
$small-radius: 4px;
$height: 80px;

.search-container {
  padding-top: 70px;
  display: flex;
  justify-content: center;
  color: #fff;
}

.search-box-wrapper {
  .search-row {
    display: flex;
    align-items: center;
    width: 1400px;
    height: 80px;
    position: relative;

    .dropdown,
    .search-input,
    .search-btn,
    .advanced-search-btn,
    .reset-btn {
      padding: 0 15px;
      box-sizing: border-box;
      border: none;
      outline: none;
    }

    .dropdown {
      display: flex;
      align-items: center;
      gap: 6px;
      background-color: #fff;
      justify-content: space-evenly;
      color: $text-color;
      border-top-left-radius: $border-radius;
      border-bottom-left-radius: $border-radius;
      cursor: pointer;
      height: 80px;
      width: 122px;
      .dropdown-options {
        position: absolute;
        top: 107%;
        left: 0;
        right: 0;
        background-color: #fff;
        border: 1px solid #eee;
        border-top: none;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        z-index: 10;
        margin: 0;
        padding: 10px;
        list-style: none;
        min-height: 300px;
        overflow: hidden;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 18px;
        width: 98px;
        border-radius: 4px;

        .dropdown-option {
          text-align: center;
          padding: 10px 15px;
          color: $text-color;
          font-size: 16px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          cursor: pointer;
          white-space: nowrap; // 防止文本换行
          overflow: hidden; // 隐藏溢出内容
          text-overflow: ellipsis; // 显示省略号
          &:hover {
            border-radius: 5px;
            background-color: #f5f7fa;
          }

          &[aria-selected="true"] {
            border-radius: 5px;
            background-color: #e8f0fe;
            color: $primary-color;
          }
        }
      }
    }

    .search-input {
      padding-left: 30px;
      // flex: 1;
      width: 1119px;
      height: $height;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      border-top-right-radius: $border-radius;
      border-bottom-right-radius: $border-radius;

      &::placeholder {
        color: #999;
        font-size: 14px;
      }
    }

    .search-panel {
      position: absolute;
      top: 100%;
      left: 122px;
      right: 302px;
      width: 1006px;
      background: #ffffff;
      box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.14);
      border-radius: 8px;
      z-index: 9;
      display: flex;
      flex-direction: column;
      padding: 0 36px 23px;
      gap: 20px;
      margin-top: 6px;

      .panel {
        display: flex;
        gap: 20px;
      }

      .pagination {
        display: flex;
        justify-content: flex-end;
      }

      .pagination11 {
        position: relative;
        right: 24px;
        bottom: -36px;

        .tong {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 120px;
          height: 48px;
          background: #327dff;
          border-radius: 0px 0px 0px 8px;
        }
      }

      .panel-column {
        flex: 1;
        height: 450px;

        .title {
          display: flex;
          justify-content: space-between;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 20px;
          color: #333333;
          height: 50px;
          align-items: center;

          .title-hun {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 16px;
            color: #327dff;
          }

          border-bottom: 1px solid #e4e4e4;
        }

        ul {
          list-style: none;
          padding: 0;

          li {
            display: flex;
            justify-content: space-between;
            cursor: pointer;
            padding: 10px 0;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 16px;
            color: #333333;

            .zi:hover {
              color: #0071d0;
            }
          }
        }
      }
    }

    .search-btn-wrapper {
      position: absolute;
      right: 158px;
      height: $height;
      display: flex;
      align-items: center;
      padding-right: 8px;
      background: #fff;
      border-top-right-radius: $border-radius;
      border-bottom-right-radius: $border-radius;

      .search-btn {
        width: 121px;
        height: 64px;
        background: $primary-color;
        border-radius: $small-radius;

        &:hover,
        &:focus {
          background: #1e6fff;
          transform: translateY(-1px);
        }
      }
    }

    .advanced-search-btn {
      background: $secondary-color;
      width: 144px;
      height: $height;
      color: #fff;
      cursor: pointer;
      margin-left: 14px;
      border-radius: $small-radius;
      font-size: 14px;

      &:hover,
      &:focus {
        background: #6b9eff;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }

    .reset-btn {
      background: #f5f7fa;
      color: #666;
      border: 1px solid #e4e4e4;
      border-radius: $small-radius;
      height: $height;
      padding: 0 15px;
      margin-left: 10px;
      cursor: pointer;
      font-size: 14px;

      &:hover {
        background: #e8f0fe;
        color: $primary-color;
        border-color: #d0e0fd;
      }
    }
  }

  .search-tags {
    width: 1400px;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-top: 24px;
    margin-bottom: 48px;

    ::v-deep .el-checkbox {
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #ffffff !important;
    }

    ::v-deep .el-checkbox__input.is-checked+.el-checkbox__label {
      color: #ffffff !important;
    }

    ::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #ffae42 !important;
      border-color: #ffae42 !important;
    }

    ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
    .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #ffae42 !important;
      border-color: #ffae42 !important;
    }

    .tag-item {
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 6px;
      margin-right: 30px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #ffffff;

      input[type="checkbox"] {
        width: 14px;
        height: 14px;
        accent-color: #ffae42;
        cursor: pointer;
      }
    }
  }
}
</style>